
package cn.itsource.system.aop;



import cn.itsource.system.domain.Log;
import cn.itsource.system.mapper.LogMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class LogManager {
    @Autowired
    private LogMapper logMapper;

    @Around("execution(* cn.itsource.*.service.I*Service.*(..))")
    //对加了@Logs注解的方法才记录日志
//    @Around("@annotation(cn.itsource.annotation.Logs)")
    public Object addLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Log log = new Log();
        // 设置操作时间为 当前时间
        log.setOperTime(new Date());
        String className = joinPoint.getSignature().getDeclaringTypeName();
        log.setClassName(className);
        String methodName = joinPoint.getSignature().getName();
        log.setMethodName(methodName);
        Object[] args = joinPoint.getArgs();
//        log.setMethodParams(Arrays.asList(args).toString());

        //获取执行时间
        long start = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();//执行目标方法
        long end = System.currentTimeMillis();
//        log.setCostTime(end - start);

        //返回值 @TODO
        Signature signature = joinPoint.getSignature();
        if (signature instanceof MethodSignature) {
            MethodSignature methodSignature = (MethodSignature) signature;
            // 实例化
            String returnType = methodSignature.getReturnType().getName();
            log.setReturnValue(returnType);
        }

        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (attributes instanceof ServletRequestAttributes) {
            HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
            String ip = request.getRemoteAddr();
            // 使用ip进行后续操作
            log.setIp(ip);
        }
//        //获取ip地址
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = attributes.getRequest();
//        String ip = request.getRemoteAddr();
//        log.setIp(ip);

        logMapper.add(log);
        return proceed;
    }

}
